package com.jimet.objects;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class JimetObject {


	protected Class<?> db;
	
	protected Thread t = Thread.currentThread();
	protected ClassLoader cl = t.getContextClassLoader();
	
	public JimetObject() {

	}

	public void load(long id) throws Exception
	{
		
		JimetDB jimetDb = (JimetDB) db.newInstance();
		TemplateUtil util = new TemplateUtil();
		
		ResultSet rs = jimetDb.loadById(id);
		LinkedHashMap<String, String> dbFieldProp = jimetDb.getDbFieldProp();
		
		Iterator<String> iter = dbFieldProp.keySet().iterator();
		Class<?> wrapperClass = this.getClass();		
		while(rs.next())
		{

			while(iter.hasNext())
			{
				String key = iter.next();
				Field field = wrapperClass.getDeclaredField(key);
				
				Method mt 	= null;
				try {
					Field clobField = wrapperClass.getDeclaredField(key+"CLOB");
					mt = wrapperClass.getMethod("set"+util.getFirstCaseUpper(key+"CLOB"),clobField.getType());
				}
				catch ( NoSuchFieldException nsfEx ) {
					mt 	= wrapperClass.getMethod("set"+util.getFirstCaseUpper(key),field.getType());
				}
				mt.invoke(this, rs.getObject(key));
				
			}			
		}
		jimetDb.disconnect();
	}	
	
	public long store() throws Exception 
	{
		Class<?> wrapperClass = this.getClass();		
		Method mt = wrapperClass.getMethod("getId");
		JimetDB jimetDb = (JimetDB) db.newInstance();
		
		long id=-1;
		if(Long.parseLong(mt.invoke(this).toString())==-1)
		{
			id = jimetDb.add(this);
		}
		else
		{
			id = jimetDb.update(this);
		}
		jimetDb.disconnect();
		return id;
	}
	
	public long storeBD() throws Exception 
	{
		Class<?> wrapperClass = this.getClass();		
		Method mt = wrapperClass.getMethod("getId");
		JimetDB jimetDb = (JimetDB) db.newInstance();
		
		long id=-1;
		if(Long.parseLong(mt.invoke(this).toString())==-1)
		{
			id = jimetDb.add(this);
		}
		else
		{
			id = jimetDb.update(this);
		}
		jimetDb.disconnect();
		return id;
	}
	
	public boolean delete() throws Exception
	{
		Class<?> wrapperClass = this.getClass();		
		Method mt = wrapperClass.getMethod("getId");
		JimetDB jimetDb = (JimetDB) db.newInstance();
		boolean res = jimetDb.delete(Long.parseLong(mt.invoke(this).toString()));
		jimetDb.disconnect();
		return res;
	}
	

	public void setDb(Class<?> db) {
		this.db = db;
	}

	public Class<?> getDb() {
		return db;
	}

}
